using CoreManager.Models.Entities;
using CoreManager.Repository.DbContext;
using SqlSugar;
using System.Linq.Expressions;

namespace CoreManager.Repository.Repositories
{
    /// <summary>
    /// SqlSugar仓储实现
    /// 基于SqlSugar ORM的高性能数据访问实现
    /// </summary>
    /// <typeparam name="T">实体类型，必须继承自BaseEntity</typeparam>
    public class SugarRepository<T> : ISugarRepository<T> where T : BaseEntity, new()
    {
        protected readonly ISqlSugarClient _sugarClient;
        protected readonly CoreManagerDbContext _context;

        public SugarRepository(ISqlSugarClient sugarClient, CoreManagerDbContext context)
        {
            _sugarClient = sugarClient;
            _context = context;
        }

        public ISqlSugarClient SugarClient => _sugarClient;
        public CoreManagerDbContext Context => _context;

        #region 基础CRUD操作

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        public async Task<T?> GetByIdAsync(int id)
        {
            return await _sugarClient.Queryable<T>().InSingleAsync(id);
        }

        /// <summary>
        /// 根据条件获取单个实体
        /// </summary>
        public async Task<T?> GetAsync(Expression<Func<T, bool>> expression)
        {
            return await _sugarClient.Queryable<T>().FirstAsync(expression);
        }

        /// <summary>
        /// 获取所有实体
        /// </summary>
        public async Task<List<T>> GetAllAsync()
        {
            return await _sugarClient.Queryable<T>().ToListAsync();
        }

        /// <summary>
        /// 根据条件获取实体列表
        /// </summary>
        public async Task<List<T>> GetListAsync(Expression<Func<T, bool>> expression)
        {
            return await _sugarClient.Queryable<T>().Where(expression).ToListAsync();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<(List<T> Items, int Total)> GetPagedListAsync(
            Expression<Func<T, bool>>? expression = null,
            int pageIndex = 1,
            int pageSize = 20,
            Expression<Func<T, object>>? orderBy = null,
            bool isAsc = true)
        {
            var query = _sugarClient.Queryable<T>();

            // 添加查询条件
            if (expression != null)
            {
                query = query.Where(expression);
            }

            // 添加排序
            if (orderBy != null)
            {
                query = isAsc ? query.OrderBy(orderBy) : query.OrderByDescending(orderBy);
            }

            // 获取总数
            var total = await query.CountAsync();

            // 分页查询
            var items = await query.ToPageListAsync(pageIndex, pageSize);

            return (items, total);
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        public async Task<int> InsertAsync(T entity)
        {
            entity.CreateTime = DateTime.Now;
            entity.UpdateTime = DateTime.Now;
            return await _sugarClient.Insertable(entity).ExecuteReturnIdentityAsync();
        }

        /// <summary>
        /// 批量添加实体
        /// </summary>
        public async Task<int> InsertRangeAsync(List<T> entities)
        {
            var now = DateTime.Now;
            entities.ForEach(e =>
            {
                e.CreateTime = now;
                e.UpdateTime = now;
            });
            return await _sugarClient.Insertable(entities).ExecuteCommandAsync();
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        public async Task<bool> UpdateAsync(T entity)
        {
            entity.UpdateTime = DateTime.Now;
            return await _sugarClient.Updateable(entity).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 根据条件更新
        /// </summary>
        public async Task<bool> UpdateAsync(Expression<Func<T, bool>> expression, Expression<Func<T, T>> updateExpression)
        {
            var result = await _sugarClient.Updateable<T>()
                .SetColumns(updateExpression)
                .Where(expression)
                .ExecuteCommandAsync();
            return result > 0;
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        public async Task<bool> DeleteAsync(int id)
        {
            return await _sugarClient.Deleteable<T>().In(id).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 根据条件删除
        /// </summary>
        public async Task<bool> DeleteAsync(Expression<Func<T, bool>> expression)
        {
            return await _sugarClient.Deleteable<T>().Where(expression).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 软删除
        /// </summary>
        public async Task<bool> SoftDeleteAsync(int id)
        {
            return await _sugarClient.Updateable<T>()
                .SetColumns(it => new T { IsDeleted = true, UpdateTime = DateTime.Now })
                .Where(it => it.Id == id)
                .ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 检查是否存在
        /// </summary>
        public async Task<bool> ExistsAsync(Expression<Func<T, bool>> expression)
        {
            return await _sugarClient.Queryable<T>().AnyAsync(expression);
        }

        /// <summary>
        /// 获取数量
        /// </summary>
        public async Task<int> CountAsync(Expression<Func<T, bool>>? expression = null)
        {
            var query = _sugarClient.Queryable<T>();
            if (expression != null)
            {
                query = query.Where(expression);
            }
            return await query.CountAsync();
        }

        /// <summary>
        /// 获取可查询对象（SqlSugar不支持标准IQueryable）
        /// </summary>
        public IQueryable<T> GetQueryable()
        {
            throw new NotSupportedException("SqlSugar仓储不支持标准IQueryable操作。请使用AsQueryable()方法获取ISugarQueryable<T>。");
        }

        #endregion

        #region SqlSugar特有功能

        /// <summary>
        /// 获取当前实体的可查询对象
        /// </summary>
        public ISugarQueryable<T> AsQueryable()
        {
            return _sugarClient.Queryable<T>();
        }

        /// <summary>
        /// 执行原生SQL查询
        /// </summary>
        public async Task<List<T>> SqlQueryAsync(string sql, object? parameters = null)
        {
            return await _sugarClient.SqlQueryable<T>(sql).AddParameters(parameters).ToListAsync();
        }

        /// <summary>
        /// 执行原生SQL命令
        /// </summary>
        public async Task<int> ExecuteSqlAsync(string sql, object? parameters = null)
        {
            return await _sugarClient.Ado.ExecuteCommandAsync(sql, parameters);
        }

        /// <summary>
        /// 批量插入（高性能）
        /// </summary>
        public async Task<int> BulkInsertAsync(List<T> entities)
        {
            var now = DateTime.Now;
            entities.ForEach(e =>
            {
                e.CreateTime = now;
                e.UpdateTime = now;
            });
            return await _sugarClient.Fastest<T>().BulkCopyAsync(entities);
        }

        /// <summary>
        /// 批量更新（高性能）
        /// </summary>
        public async Task<int> BulkUpdateAsync(List<T> entities)
        {
            entities.ForEach(e => e.UpdateTime = DateTime.Now);
            return await _sugarClient.Fastest<T>().BulkUpdateAsync(entities);
        }

        /// <summary>
        /// 批量删除（高性能）
        /// </summary>
        public async Task<int> BulkDeleteAsync(Expression<Func<T, bool>> expression)
        {
            return await _sugarClient.Deleteable<T>().Where(expression).ExecuteCommandAsync();
        }

        /// <summary>
        /// 开始事务
        /// </summary>
        public ITenant BeginTransaction()
        {
            return _sugarClient.AsTenant();
        }

        /// <summary>
        /// 复杂查询构建器
        /// </summary>
        public ISugarQueryable<T> Queryable()
        {
            return _sugarClient.Queryable<T>();
        }

        #endregion
    }
}